package cn.yi.boot.shiro.security;

import cn.yi.boot.shiro.UserCons;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import yi.boot.common.security.constant.Constant;
import yi.boot.common.security.dto.BaseShiroMenu;
import yi.boot.common.security.dto.BaseShiroUser;

import java.util.*;

/**
 * 需要查询用户的相关信息
 */
public class UserRealm extends AuthorizingRealm {

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        BaseShiroUser user = (BaseShiroUser)principals.getPrimaryPrincipal();
        Integer isAdmin = user.getIsAdmin();

        List<String> permsList;

        //系统管理员，拥有最高权限
        if(isAdmin == Constant.SUPER_ADMIN){
            List<BaseShiroMenu> menuList = Lists.newArrayList(); // TODO sysMenuDao.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for(BaseShiroMenu menu : menuList){
                //获取菜单授权 perms(多个用逗号分隔，如：user:list,user:create)
                permsList.add(menu.getPerms());
            }
        }else{
            //查询用户的所有权限
            permsList = Lists.newArrayList();// TODO sysUserDao.queryAllPerms(userId);
        }

        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        //获取到用户传入的用户名+密码
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        //查询用户信息
        BaseShiroUser user = UserCons.getBaseUser();//TODO
        user.setUsername(token.getUsername());

        //账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
        return info;
    }

  /*  @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
        shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
        super.setCredentialsMatcher(shaCredentialsMatcher);
    }
*/
}
